package com.reps.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.jsoup.Jsoup;

import com.reps.RepsStartMain;
import com.reps.util.TreeUtil;

import lombok.extern.log4j.Log4j;

/**
 * @author chl
 * @date 2018/7/19 20:57
 */
@Log4j
public class DowloadThreadNew extends Thread {

    private    int begin;
    private    int end;


    public DowloadThreadNew(int begin,int end,String name)
    {
        this.begin=begin;
        this.end=end;
        super.setName(name);

    }

    @Override
    public void run() {

        try
        {
            getDataForOneVillage(begin,end);
            Integer next=null;
            while((next= RepsStartMain.getNext())!=null)
            {
                getDataForOneVillage(next,next+1);
            }
        }catch (Exception e)
        {
            e.printStackTrace();
        }



    }


    public  void getDataForOneVillage(int start,int person_num) throws Exception
    {

        Thread t = Thread.currentThread();
        String name = t.getName();
        System.out.println("当前线程名称：" + name);log.info("当前线程名称：" + name);
        for(int i=start;i<person_num;i++)
        {
            Thread t1 = Thread.currentThread();
            String name1 = t1.getName();
            System.out.println("当前线程名称：" + name1+",正在处理用户："+i);
            log.info("当前线程名称：" + name1+",正在处理用户："+i);
            String xmlInfo="<?xml version=\"1.0\" encoding=\"UTF-8\"?><client><changes><window wid=\"desktop\"><control cid=\""+ RepsStartMain.dtwinid+"\"><_1344><![CDATA[<change_data><data realSel='"+ i +"' cellIndex='0'></data></change_data>]]></_1344></control></window></changes><sequenceid>null</sequenceid><event Controlid=\""+ RepsStartMain.dtwinid+"\" winid=\"desktop\" parameter=\""+ RepsStartMain.dtwinid+",aHRtbENhbGwjdGlqaWFuZGo=\" eventtype=\"a\"/></client>";
            getDataForOnePerson(xmlInfo);
        }

    }


    public  void getDataForOnePerson(String para_xml) throws Exception
    {
        String url="http://"+RepsStartMain.dtHostPort+"/dtvhcis/start?WAT=CONTROLLER";
        // int pid=46;//体检者id
        Map map=new HashMap<String,String>();
        String xmlInfo=para_xml.trim();
        String winid=new String("dx_22782_");
        String lookcontrolid=new String("dx_14541_");//点击的哪个按钮，此处表示点击  查看  按钮
        String tableId=new String("dx_14520_");//选中列表中要查看某条记录所在表的id
        String rowid=new String("0");//选中的某行的id
        int rowNum=0;//该体检者总共有多少条体检记录，如果是0则不请求



        File fileDir = new File("F:\\镇上的数据\\"+"444\\");
        if(!fileDir.exists()){
            fileDir.mkdirs();
        }
        String filePath1="F:\\镇上的数据\\444\\t.xml";
        String filePath1_1="F:\\镇上的数据\\444\\1_1.xml";


        Element root= null;
        try {
            System.out.println(xmlInfo);log.info(xmlInfo);
            root = post(url,xmlInfo,filePath1);

        } catch (Exception e) {
            root = post(url,xmlInfo,filePath1);
            e.printStackTrace();
        }


        Element element_template=TreeUtil.getByNodeName(TreeUtil.getByNodeName(root,"templates"),"template");

        //获取tableId
        Element element_changes=TreeUtil.getByNodeName(root,"changes");
        List<Element> element_list_window= element_changes.elements();

        for(Element e:element_list_window)
        {
            if(e.content().size()==2)
            {
                Element winElement=(Element)e.elements().get(1);
                tableId=winElement.attributeValue("cid");
                Element eee=(Element) winElement.elements().get(2);
                rowNum=Integer.valueOf(eee.getText());//获取该检查者的体检总记录数
                break;
            }

        }



        //获取winid
        winid = element_template.attributeValue("tid");

        //获取controllid
        Element element_content=(Element) element_template.elements().get(0);
        String html=(String)element_content.getData();
        org.jsoup.nodes.Document rootDoc = Jsoup.parse(html);
        org.jsoup.nodes.Element element_body=rootDoc.body();
        org.jsoup.nodes.Element element_menubar=element_body.getElementById("menubar");
        org.jsoup.nodes.Element element_span=element_menubar.child(0);
        org.jsoup.nodes.Element element_span_look=element_span.child(0).child(1).child(1).child(1).child(0);
        lookcontrolid=element_span_look.child(0).child(0).child(1).attr("id").replace("_text","");
        map.put("winid",winid);
        map.put("tableId",tableId);
        map.put("lookcontrolid",lookcontrolid);
        map.put("rowid",rowid);
        map.put("rowNum",rowNum);


        int num=Integer.valueOf(map.get("rowNum").toString());
        if(num>0)
        {
            //循环遍历每一次体检记录
            for(int i=0;i<num;i++)
            {
                String xmlInfo_person="<?xml version=\"1.0\" encoding=\"UTF-8\"?><client><changes><window wid=\""+map.get("winid")+"\" state=\"1\" top=\"307\" left=\"628\" width=\"668\" height=\"400\" active=\"true\">" +
                        "<control cid=\""+map.get("tableId")+"\"><_1344><![CDATA[<change_data><data realSel='"+i+"'>" +
                        "</data></change_data>]]></_1344></control></window></changes>" +
                        "<sequenceid>null</sequenceid><event Controlid=\""+map.get("lookcontrolid")+"\" winid=\""+map.get("winid")+"\" parameter=\""+map.get("lookcontrolid")+",cHJlc3M=\" eventtype=\"a\"/></client>";
                filePath1_1="F:\\镇上的数据\\444\\"+String.valueOf(i)+".xml";
                Element element1_1;
                try {
                    System.out.println(xmlInfo_person);log.info(xmlInfo_person);
                    element1_1=post(url,xmlInfo_person,filePath1_1);


                    //解析健康体检表界面
                    Element template=TreeUtil.getByNodeName(TreeUtil.getByNodeName(element1_1,"templates"),"template");
                    Element content=(Element)template.elements().get(0);
                    Element initial=(Element)template.elements().get(1);
                    List<Element> windows=TreeUtil.getByNodeName(element1_1,"changes").elements();


                    String[] initList=initial.getText().split(";");

                    String[] window_id_temp=getValueId(initList[0]);
                    String window_id=window_id_temp[0];
                    Element window_element=null;//保存存放所有值的window
                    List<Element> window_list=windows;
                    //找出所有的值放在哪个window中
                    for(Element e:window_list)
                    {
                        if(e.attributeValue("wid").toString().equals(window_id))
                        {
                            window_element=e;
                            break;
                        }
                    }

                    List<Element> control_list=window_element.elements();
                    SetValueTemplate.setControl_list(control_list);
                    // String[] values=new String[initList.length];

                     OutInfo myvalue=new OutInfo();
                    myvalue.record+=i+";";//某个体检者的第几次体检记录
                    //myvalue.record+=initList.length+";";
                    //循环获取值
                    for(int index=0;index<182;index++)//initList.length
                    {

                        if(index==6)
                        {

                            String s=initList[index];
                            s=s.substring(s.indexOf("(")+1,s.length()-1);
                            String[] ttt=s.split("top.DxTextField.init\\(");
                            ttt[0]=ttt[0].replace("'","").replace("\\)","").split(",")[1];
                            int tttTemp=Integer.valueOf(ttt[0].split("_")[1]);
                            int startCheckbox=tttTemp+4;//病症共24个复选框，如果第一个值为1，表示无病症，不需要遍历其他
                            String bingzhengid="dx_"+startCheckbox+"_";
                            SetValueTemplate.setValue(bingzhengid, control_list, new ProcessOneProperty() {
                                @Override
                                public void process(List<Element> e) throws Exception {
                                    String checkbox=String.valueOf(e.get(0).getText().split("\\$")[1]);
                                    myvalue.record+=checkbox+",";
                                    if(!checkbox.equals("1"))
                                    {
                                        for(int i=1;i<24;i++)
                                        {
                                            String nextbingzhengid="dx_"+(startCheckbox+i)+"_";
                                            SetValueTemplate.setValue(nextbingzhengid, control_list, new ProcessOneProperty() {
                                                @Override
                                                public void process(List<Element> e) throws Exception {
                                                    String checkbox=String.valueOf(e.get(0).getText().split("\\$")[1]);
                                                    myvalue.record+=checkbox+",";
                                                }
                                            });
                                        }
                                    }
                                    myvalue.record+=";";


                                }
                            });
                            //获取其他症状信息
                            String qitaid=ttt[1].replace("'","").split(",")[1];
                            SetValueTemplate.setValue(qitaid, control_list, new ProcessOneProperty() {
                                @Override
                                public void process(List<Element> e) throws Exception {
                                    myvalue.record+=e.get(0).getText()+";";
                                }
                            });





                        }
                        else if(index!=6)
                        {
                            String[] win_value=getValueId(initList[index]);
                            //处理普通的值
                            if(win_value.length==2)
                            {
                                int indexOfControl_list=0;
                                for(Element e:control_list)
                                {
                                   /* if(index==87 || index==91 || index==85)
                                        break;*/

                                    indexOfControl_list++;

                                    if(e.attributeValue("cid")==null)
                                    {
                                        if(indexOfControl_list==control_list.size())
                                        {
                                             if(index==84)//空腹血糖：值2
                                             {
                                                 int win_id=Integer.valueOf(win_value[1].replace("dx","").replace("_",""));
                                                 myvalue.record+= SetValueTemplate.getMultiCheckboxValueString(win_id+3,1)+";";
                                             }
                                             else{
                                                 myvalue.record+=" ;";
                                                 //空控件后面的控件可能优质
                                                 //PrcessValue.processTwoParameterAfter(index,myvalue,win_value);
                                             }
                                        }
                                        continue;
                                    }

                                    if(e.attributeValue("cid").equals(win_value[1]))
                                    {
                                        List<Element> temp=e.elements();
                                        if(index>=10 && index<=13)//血压数据
                                        {
                                            myvalue.record+=temp.get(1).getText()+";";
                                            break;
                                        }
                                        if(index==18)//智力等：总分
                                        {
                                            myvalue.record+=temp.get(1).getText()+";";
                                            //1 复选框 老年人情感状态
                                            int win_id=Integer.valueOf(win_value[1].replace("dx","").replace("_",""));
                                            myvalue.record+= SetValueTemplate.getMultiCheckboxValueString(win_id+1,1)+";";
                                            break;
                                        }
                                        if(index>=24 && index<=47)
                                        {
                                            if(temp.size()==1)
                                                myvalue.record+=temp.get(0).getText()+";";
                                            else
                                            {
                                                if(temp.get(0).getText().contains("true")|| temp.get(0).getText().contains("false"))
                                                    myvalue.record+=temp.get(1).getText()+";";
                                                else
                                                    myvalue.record+=temp.get(0).getText()+";";
                                            }//此处不加break；
                                        }else if(index>=69 && index <=73)
                                        {
                                            if(temp.size()==2)
                                            {
                                                myvalue.record+=temp.get(1).getText()+";";
                                            }
                                            else
                                                myvalue.record+=temp.get(0).getText()+";";
                                            //没有break;
                                        }


                                        if(index==86) //心电图异常备注
                                        {
                                            if(temp.size()==2)
                                            {
                                                myvalue.record+=temp.get(1).getText()+";";
                                            }
                                            else
                                                myvalue.record+=temp.get(0).getText()+";";
                                            break;
                                        }

                                        if(index==108 || index==109 || index==110)
                                        {
                                            if(temp.size()==2)
                                            {
                                                myvalue.record+=temp.get(1).getText()+";";
                                            }
                                            else
                                                myvalue.record+=temp.get(0).getText()+";";

                                            //没有break;
                                        }



                                           if((index>=24 && index<=47) || (index>=69 && index <=73) || (index>=69 && index <=73) || (index==108 || index==109 || index==110))
                                           {}
                                           else
                                               myvalue.record+=temp.get(0).getText()+";";




                                        PrcessValue.processTwoParameterAfter(index,myvalue,win_value);

                                        break;

                                    }
                                }

                            }
                            else if(win_value.length==5 || win_value.length==4)
                            {



                                int indexOfControl_list=0;
                                for(Element e:control_list)
                                {

                                    indexOfControl_list++;

                                    if(e.attributeValue("cid")==null)
                                    {
                                        if(indexOfControl_list==control_list.size())
                                        {

                                            myvalue.record+=";";

                                            //PrcessValue.processFiveParameterAfter(index,myvalue,win_value);
                                        }
                                        continue;
                                    }

                                    //特殊，有可能找不到，每个都是下拉列表，存储下标志，尿常规：尿蛋白，尿    糖，尿酮体，尿潜血
                                    if(index==78)
                                    {
                                        int win_id=Integer.valueOf(win_value[1].replace("dx","").replace("_",""));
                                        for(int j=0;j<4;j++)
                                        {
                                            String temp= SetValueTemplate.getOneValueByWinId3(win_id+j*8);
                                            if(temp.equals(""))
                                                myvalue.record+="-1,";
                                            else
                                                myvalue.record+=temp+",";
                                        }
                                        myvalue.record+=";";
                                        break;
                                    }
                                    if(index==79 || index==80 || index==81)
                                        break;

                                    if(index==111)//中医体质辨识
                                    {
                                        int win_id=Integer.valueOf(win_value[1].replace("dx","").replace("_",""));
                                        myvalue.record+= SetValueTemplate.getMultiCheckboxValueString(win_id,9)+";";
                                        //5个复选框   脑血管疾病
                                        myvalue.record+= SetValueTemplate.getMultiCheckboxValueString(win_id+58,5)+";";
                                        break;
                                    }
                                    if(index>=112 && index<=119)
                                        break;






                                    if(e.attributeValue("cid").equals(win_value[1].trim()))
                                    {
                                        List<Element> temp=e.elements();

                                      boolean flag= PrcessValue.processFiveParameterBefore(index,myvalue,temp,win_value);
                                      if(flag)
                                          break;


                                            myvalue.record+=temp.get(0).getText()+";";

                                      PrcessValue.processFiveParameterAfter(index,myvalue,win_value);

                                        break;
                                    }
                                }


                            }


                        }
                    }

                    //保存这条体检记录信息 myvalue.record
                    System.out.println("字段数量："+getSpecialCharNumber(myvalue.record)+"---"+myvalue.record);
                    log.info(("字段数量："+getSpecialCharNumber(myvalue.record)+"---"+myvalue.record));
                    SaveRecordInfo.saveOneRecord(myvalue.record);

                    org.jsoup.nodes.Document doc = Jsoup.parse(content.getText());
                    org.jsoup.nodes.Element doc_content=doc.getElementById("content");

                    String sss="";

                } catch (Exception e) {
                    element1_1=post(url,xmlInfo_person,filePath1_1);
                    e.printStackTrace();
                }
            }
        }
    }


    private int getSpecialCharNumber(String s)
    {
        int i=0;
        char[] chars=s.toCharArray();
        for(char c:chars)
        {
            if(String.valueOf(c).equals(";"))
                i++;
        }
        return i;
    }

    private  String[] getValueId(String s)
    {
        s=s.substring(s.indexOf("(")+1,s.length()-1);
        s=s.replace("'","");
        String[] tt=s.split(",");
        return tt;
    }

    private  Element post(String url, String xmlInfo, String fileFullPath) throws Exception
    {

        File file = new File(fileFullPath);

       // FileOutputStream out=new FileOutputStream(file,false); //如果追加方式用true
       // StringBuffer sb=new StringBuffer();

        String res =  testPost(url,xmlInfo);

       // out.write(res.getBytes("utf-8"));//注意需要转换对应的字符集
       // out.close();
        res=res.trim();
/*        Pattern p = Pattern.compile(">(\\s*|\n|\t|\r)<");  
        Matcher m = p.matcher(res);  
        res = m.replaceAll("><");  */
        Document document = DocumentHelper.parseText(res);
        Element root = document.getRootElement();

        return root;
    }


    /**
     * 用传统的URI类进行请求
     * @param urlStr
     */
    private  String testPost(String urlStr,String xmlInfo) {
    	 StringBuilder rs=new StringBuilder();
       
        try {
            URL url = new URL(urlStr);

            HttpURLConnection con = (HttpURLConnection)url.openConnection();
            con.setConnectTimeout(10000);
            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setDoInput(true);
            // 设置通用的请求属性
            con.setRequestProperty("Content-Type","text/xml");
            con.setRequestProperty("Accept", "*/*");
            con.setRequestProperty("Accept-Encoding", "gzip, deflate");
            con.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");
            con.setRequestProperty("Connection", "keep-alive");
            //con.setRequestProperty("Content-Length", "329");
            con.setRequestProperty("Content-Type", "text/html UTF-8");

            con.setRequestProperty("Host",RepsStartMain.dtHostPort);
            con.setRequestProperty("Referer","http://"+RepsStartMain.dtHostPort+"/dtvhcis/start");
            con.setConnectTimeout(600*1000);
            con.setRequestProperty("User-Agent",
                    "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E)");
            con.setRequestProperty("Cookie", "LoginCode_name="+ RepsStartMain.dtUserName+"; JSESSIONID="+ RepsStartMain.dtjssesionid);// 给服务器送登录后的cookie

            OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());

            out.write(new String(xmlInfo.getBytes("UTF-8")));
            out.flush();
            out.close();
            BufferedReader br = new BufferedReader(new InputStreamReader(con
                    .getInputStream(),"UTF-8"));
            String line = null;
           
            for (line = br.readLine(); line != null; line = br.readLine()) {
            	rs.append(line);
            }

            br.close();
            con.getInputStream().close();

        } catch (Exception e) {

            e.printStackTrace();
        }
        log.info(xmlInfo+"==request-response=="+rs.toString());
        return rs.toString();
    }





}
